package org.catpay.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.catpay.common.utils.CommonMap;
import org.catpay.modules.sys.dao.SysUserRoleDao;
import org.catpay.modules.sys.entity.SysUserRoleEntity;
import org.catpay.modules.sys.service.SysUserRoleService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

/**
 * 用户与角色对应关系
 * 
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRoleEntity>
		implements SysUserRoleService {

	@Override
	public void saveOrUpdate(Long userId, List<Long> roleIdList) {
		// 先删除用户与角色关系
		this.deleteByMap(CommonMap.getMap().put("user_id", userId));

		if (roleIdList == null || roleIdList.size() == 0) {
			return;
		}

		// 保存用户与角色关系
		List<SysUserRoleEntity> list = new ArrayList<>(roleIdList.size());
		for (Long roleId : roleIdList) {
			SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
			sysUserRoleEntity.setUserId(userId);
			sysUserRoleEntity.setRoleId(roleId);
			list.add(sysUserRoleEntity);
		}
		this.insertBatch(list);
	}

	@Override
	public List<Long> queryRoleIdList(Long userId) {
		List<SysUserRoleEntity> list = new SysUserRoleEntity()
				.selectList(new EntityWrapper<>().setSqlSelect("role_id").eq("user_id", userId));
		List<Long> result = new ArrayList<>();
		list.forEach(sur -> {
			result.add(sur.getRoleId());
		});
		return result;
	}

	@Override
	public boolean deleteBatch(Long[] roleIds) {
		return new SysUserRoleEntity().delete(new EntityWrapper<>().in("role_id", roleIds));
	}
}
